#include "Client.h"
int Command(char *cmd){
    if(strcmp(cmd, "cd") == 0){
        return CD;
    }else if(strcmp(cmd, "ls") == 0){
        return LS;
    }else if(strcmp(cmd, "pwd") == 0){
        return PWD;
    }else if(strcmp(cmd, "puts") == 0){
        return PUTS;
    }else if(strcmp(cmd, "gets") == 0){
        return GETS;
    }else if(strcmp(cmd, "remove") == 0){
        return REMOVE;
    }else if(strcmp(cmd, "mkdir") == 0){
        return MKDIR;
    }else if(strcmp(cmd, "rmdir") == 0){
        return RMDIR;
    }else{
        return -1;
    }
}
int SendCommand(int sockfd, char* buf){
    //后续考虑将其他信号都传出去
    char *cmd = strtok(buf, " \n");
    if(cmd == NULL){
        return 0;
    }
    int sig_t = Command(cmd);
    char *msgcmd = strtok(NULL, " \n");

    if(msgcmd == NULL && (sig_t < CD || sig_t > PWD)){ // cd\ls\pwd命令不需要参数
        return 0;
    }else if(strtok(NULL, " \n") != NULL){
        return 0;
    }

    SignalSend_t *sig = (SignalSend_t *)calloc(1, sizeof(SignalSend_t));
    sig->sig_t = sig_t;
    switch(sig_t){

    case CD:
    case LS:
    case PWD:
    case PUTS:
    case GETS:
    case REMOVE:
    case MKDIR:
    case RMDIR:
        if(msgcmd != NULL){
            if(strncmp(msgcmd, "/", 1) == 0){
                memcpy(sig->pathname[sig->size], "/", sizeof("/"));
                ++ sig->size;
            }
            char *msg = strtok(msgcmd, "/"); 
            while (msg != NULL && sig->size <= DEPTH){
                memcpy(sig->pathname[sig->size], msg, strlen(msg));
                ++ sig->size;
                //printf("%s\n",sig->pathname[sig->size]);
                msg = strtok(NULL, "/"); 
            }
        }
        // 信号 路径段的个数 路径段 路径
        printf("sig_t == %d,size == %d\n",sig->sig_t,sig->size);
        send(sockfd, sig, sizeof(SignalSend_t), 0);
        if(sig_t == PUTS){
            TransFile(sockfd, msgcmd);
        }else if(sig_t == GETS){
            if(RecvFile(sockfd) == -1){
                printf("Error GETS file\n");
            }    
        }
        break;
    default:
        printf("default %s\n", buf);
        break;
    }
    free(sig);
    return 0;
}
int RecvMsg(int sockfd){
    //接收到信号值
    FileBuf_t *msg = (FileBuf_t *)malloc(sizeof(FileBuf_t));
    memset(msg, 0, sizeof(FileBuf_t));
    ssize_t ret = recv(sockfd, msg, sizeof(FileBuf_t), 0);
    if(ret <= 0){
        printf("Server exit\n");
        return -1;
    }
    printf("%s\n", msg->buf);
    free(msg);
    return 0;
}
